/**
 * Google Reader web app script
 */

function n(app, msg) {
  window.platform.showNotification(app, msg, null); 
}

/**
 * standard webrunner plugin api
 */
function startup() {
}

function preload() {
}

function load() {        
	Reader.load();
}

function shutdown() {
	Reader.shutdown();
}

function error() {
}

var Reader = {
	_timer : null,
	_unreadCount : 0,
	_window : null,

	receiveMessage : function() {      
		//window.platform.sound().beep();
		window.platform.getAttention();

		n("Google Reader", "You have " + Reader._unreadCount + " unread item(s)."); 
	},

	_init : function() {
		Reader._unreadCount = 0;
		Reader._window = window;
	},
	
	run : function() {
		if (Reader._unreadCount == undefined)
		Reader._unreadCount = 0;

		var title = Reader._window.top.document.title;

		var matches = title.match(/Google Reader \((\d+)\)/);
		if (matches) {      
			if (matches[1] > Reader._unreadCount) {
				 Reader._unreadCount = matches[1];
				 Reader.receiveMessage();
			}

			Reader._unreadCount = matches[1]; 
		}
	},

	load : function() {    
		Reader._init();
		// kick off a polling timer to check for new articles
		Reader._timer = Reader._window.setInterval(Reader.run, 5000);
	},

	shutdown : function() {    
		if (Reader._timer)
			Reader._window.clearInterval(Reader._timer);
	}
};
